// Package layer_range_tree 2-107
// @Title layer_range_tree
// @Description
// @Author  == 琳琳也叫王木木 ==  2021/9/16 13:58
// @Create  2021/9/16 13:58
package layer_range_tree

// 自底向上的二叉树层序遍历
func LevelOrderBottom(root *TreeNode) [][]int {
	if root == nil {
		return nil
	}
	ans := [][]int{}
	stack := [][]int{}
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		size := len(queue)
		tempArr := []int{}
		for i := 0; i < size; i++ {
			node := queue[0]
			queue = queue[1:]
			tempArr = append(tempArr, node.Val)
			if node.Left != nil {
				queue = append(queue, node.Left)
			}
			if node.Right != nil {
				queue = append(queue, node.Right)
			}
		}
		stack = append(stack, tempArr)
	}
	for len(stack) > 0 {
		ans = append(ans, stack[len(stack)-1])
		stack = stack[:len(stack)-1]
	}
	return ans
}
